#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   option.py
@Time    :   2024/01/21 17:53:12
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   浏览器操作
'''

from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import Chrome

from rpa_tool import init_chrome_driver


# 浏览器控制类
class Browser():
    
    # 浏览器初始化
    def __init__(self, isHeadless:bool = False):
        """
        isHeadless: 是否使用无头浏览器模式，默认为 False
        """
        self.options = Options()
        self.options.add_experimental_option("excludeSwitches", ['enable-automation', 'enable-logging'])
        self.options.add_experimental_option('useAutomationExtension', False)
        self.options.add_experimental_option("detach", True)
        self.options.add_argument('--disable-blink-features=AutomationControlled')
        if isHeadless:
            self.options.add_argument('--headless')
        driver_path = init_chrome_driver()
        
        self.web = Chrome(driver_path, options=self.options)
        self.web.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
            'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
        })
        self.current_window = self.web.current_window_handle

    # 打开浏览器
    def open(self, url:str):
        """
        url: 打开网址
        """
        self.web.get(url)

    # 最大化
    def maximize(self):
        self.web.maximize_window()

    # 刷新
    def refresh(self):
        self.web.refresh()

    # 返回
    def back(self):
        self.web.back()

    # 前进
    def forward(self):
        self.web.forward()

    # 点击
    def click(self, selector:str):
        """
        selector: 选择器
        """
        elemnet = self.web.find_element(By.CSS_SELECTOR, selector)
        elemnet.click()

    # 输入框输入
    def keydown(self, selector:str, key:str):
        """
        selector: 选择器
        key: 输入值
        """
        element = self.web.find_element(By.CSS_SELECTOR, selector)
        element.send_keys(key)

    # 获取文本
    def get_text(self, selector:str) -> str:
        """
        selector: 选择器
        """
        element = self.web.find_element(By.CSS_SELECTOR, selector)
        return element.text
    
    # 滚动条
    def scrollBar(self, height:int):
        """
        height: 滚动高度
        """
        js = "window.scrollTo(0,{})".format(height)
        self.web.execute_script(js)

    # 打开标签页访问网址
    def open_tab(self, url):
        """
        url: 要访问的网址
        """
        js = "window.open('{}','_blank');"
        self.web.execute_script(js.format(url))
        self.web.switch_to.window(self.web.window_handles[-1])

    # 关闭标签页
    def close_tab(self):
        self.web.close()
        self.web.switch_to.window(self.current_window)

    # 等待元素加载
    def wait_for_element_with_id(self, element_id:str, max_delay:int):
        """
        element_id: 元素ID
        max_delay: 最大等待时间
        """
        wait = WebDriverWait(self.web, max_delay)
        element = wait.until(EC.presence_of_element_located((By.ID, element_id)))
        return element
    
    # 元素是否存在
    def element_exists(self, selector:str):
        """
        selector: 选择器
        """
        try:
            self.web.find_element(By.CSS_SELECTOR, selector)
            return True
        except Exception:
            return False

    # 获取页面源代码
    def get_code(self):
        return self.web.page_source

    # 关闭浏览器
    def close(self):
        self.web.close()
